import { Avatar, Button, Message, Tabs, Tooltip, Typography } from '@arco-design/web-react';
import {
  IconCamera,
  IconEdit,
  IconFaceFrownFill,
  IconHome,
  IconPhone,
  IconRedo,
  IconUser,
} from '@arco-design/web-react/icon';
import { resetUserPwdDialog, updateAccountDialog } from '@src/components/dialog';
import LoadingMask from '@src/components/loadingMask';
import main from '@src/main';
import { logoutRequest } from '@src/redux/logoutReducer';
import { userRequest } from '@src/redux/userReducer';
import { AppStore } from '@src/types';
import useDict from '@src/utils/dict';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { keepCopy } from '../../components/tableColumn';
import { apiResetPassword, apiUserUpdateInfo } from './api';
import { ReactNode, useEffect, useState } from 'react';
import { checkPermission } from '@src/components/ability';
import AccountInfo from './components/accountInfo';

const SYS_USER_SEX = 'sys_user_sex';
export default function AccountPage() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const dictDatas = useDict(SYS_USER_SEX);
  const user = useSelector((s: AppStore) => s.user?.user);
  const [tabItems, setTabItems] = useState<Array<{ key: string; label: string; children: ReactNode }>>([]);

  useEffect(() => {
    let list: Array<{ key: string; label: string; children: ReactNode }> = [];
    // if (checkPermission([''])) {
    // @ts-ignore
    list.push({
      key: '1',
      label: '账户配置',
      children: <AccountInfo />,
    });
    // }
    if (checkPermission([''])) {
      list.push({
        key: '2',
        label: '落地页配置',
        children: <div />,
      });
    }

    setTabItems(list);
  }, []);

  // 修改个人信息
  async function handleUpdateInfo() {
    if (!user) return;
    let modalRes: any = await updateAccountDialog(user, dictDatas[SYS_USER_SEX]);
    if (modalRes === 0) return;
    try {
      LoadingMask.show('正在上传...');

      let res = await apiUserUpdateInfo(Object.assign({}, modalRes, { userId: user.userId }));
      let data = res.data;
      if (data.code === 200) {
        Message.success('修改成功');
        dispatch(userRequest({ token: main.loginKey! }));
      } else {
        Message.warning(data.msg ?? '修改失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '修改失败');
    } finally {
      LoadingMask.hide();
    }
  }

  async function resetPassword() {
    let modalRes: any = await resetUserPwdDialog(user?.nickName ?? '');
    if (modalRes === 0) return;
    try {
      LoadingMask.show('正在修改...');
      let res = await apiResetPassword(user!.userId!, modalRes);
      let data = res.data;
      if (data.code === 200) {
        Message.success(data.msg ?? '修改成功');
        dispatch(logoutRequest());
        navigate('/login', { replace: true });
      } else {
        Message.warning(data.msg ?? '修改失败');
      }
    } catch (e: any) {
      Message.error(e.message ?? '修改失败');
    } finally {
      LoadingMask.hide();
    }
  }

  return (
    <div className="page account-page p-20 scroll-bar-h-min">
      <div className="account-info-block">
        <img className="account-bg" src="/pic/pic_account_bg.png" alt="" />
        <Avatar className="mb-20" size={70} triggerIcon={<IconCamera className="text-primary-color" />}>
          <img src={!!user?.avatar ? user.avatar : '/pic/pic_avatar_default.png'} alt="" />
        </Avatar>
        <div className="info d-flex-r ai-center mb-20">
          <Tooltip content="修改信息">
            <Button
              size="small"
              className="mr-30"
              shape="circle"
              type="primary"
              icon={<IconEdit onClick={handleUpdateInfo} />}
            />
          </Tooltip>
          <Tooltip content="重置密码">
            <Button
              size="small"
              shape="circle"
              type="primary"
              status="danger"
              icon={<IconRedo />}
              onClick={resetPassword}
            />
          </Tooltip>
        </div>
        <div className="info d-flex-r ai-center font-12">
          <IconUser className="mr-4" />
          <div className="mr-20">{user?.userName}</div>
          <IconFaceFrownFill className="mr-4" />
          <div className="mr-20">{user?.nickName}</div>
          <IconPhone className="mr-4" />
          <div className="mr-20">{keepCopy(user?.phonenumber)}</div>
          <IconHome className="mr-4" />
          <div>{user?.dept?.deptName}</div>
        </div>
      </div>
      <div className="bg-white mt-20 p-20 border-radius-10">
        <Tabs className="bw-100" defaultActiveTab="1">
          {tabItems.map((i) => (
            <Tabs.TabPane key={i.key} title={i.label}>
              <Typography.Paragraph>{i.children}</Typography.Paragraph>
            </Tabs.TabPane>
          ))}
        </Tabs>
      </div>
    </div>
  );
}
